package com.blockmeta.bbs.immodule.corebean.Impl;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.NewsListHomeQuery;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.ImageTools;
import com.blockmeta.bbs.baselibrary.utils.UUIDUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.pojo.MessageParam;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.baselibrary.utils.OpenFileUtil;
import com.blockmeta.bbs.businesslibrary.util.UserSharedPreferenceUtil;
import com.blockmeta.bbs.businesslibrary.websocket.IFlowManager;
import com.blockmeta.bbs.businesslibrary.widget.ForegroundCallbacks;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.ICallBack;
import com.blockmeta.bbs.immodule.SessionService;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.broadcast.IMMsgDispatcher;
import com.blockmeta.bbs.immodule.corebean.IChatMessageDomainService;
import com.blockmeta.bbs.immodule.corebean.IFileHttpService;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.ITodoDomainService;
import com.blockmeta.bbs.immodule.corebean.MsgSendQueue;
import com.blockmeta.bbs.immodule.corebean.MsgWorker;
import com.blockmeta.bbs.immodule.corebean.WaitSendQueue;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.dao.Todo;
import com.blockmeta.bbs.immodule.utils.BeepManager;
import com.blockmeta.bbs.immodule.utils.NotificationHelper;
import com.liulishuo.filedownloader.FileDownloader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import static com.blockmeta.bbs.baselibrary.utils.OpenFileUtil.getExtensionName;

/**
 * @author author chenting
 * im服务控制类,应用层，实现消息发送逻辑和接收逻辑，可以通过调用domain service manger实现功能
 * 不能被业务逻辑层调用,否则会出现循环依赖
 */
public class ImMetaManager extends IMMetaBase implements IFlowManager {
    public static final String IMSERVER = "imserver";
    private Intent mIntentService;
    private Context context;
    private MsgWorker worker;

    private SessionService mSessionService;//服务长链接代理
    protected WaitSendQueue m_waitQueue;
    protected MsgSendQueue m_MsgSendQueue;
    private boolean isBindService;
    // 消息提示音
    private BeepManager beepManager;
    /**
     * im开关
     */
    private boolean isIM = true;
    private IChatMessageDomainService messageDomainService;
    private ITodoDomainService todoDomainService;
    private IFileHttpService mFileHttpService;
    protected Handler m_handler;
    private IntentFilter beepFilter;
    private BroadcastReceiver imBeepReceiver;


    public ImMetaManager() {
        context = BaseApp.getApp();
        m_handler = new Handler();
        m_waitQueue = new WaitSendQueue(this);
        m_MsgSendQueue = new MsgSendQueue(this);
        FileDownloader.setup(context);
        messageDomainService = IMApplicationContext.getChatMessageDomainService();
        mFileHttpService = new FileHttpService(context);
        todoDomainService = IMApplicationContext.getTodoDomainService();
    }

    @Override
    public MsgWorker getWorker() {
        return worker;
    }

    //只调用一次！！！
    @Override
    public void getMessageList() {
        try {
            long fromMessageId = UserSharedPreferenceUtil.getLong(context, Constants.MAX_CHATMESSAGE_ID_LONG, 0);
            if (fromMessageId == 0) {
                //为了防止删除后获取到删除的，所以要用sp内的
                fromMessageId = messageDomainService.getMaxMessageIdByUserId(
                        mSessionService.getUserId());
            }
            mSessionService.getMessageList(fromMessageId);
            LogUtils.i("author" + fromMessageId + "----------------------fromMessageId");
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public void getChatGroupList() {
        try {
            mSessionService.getChatGroupList();
            LogUtils.i("author" + "getChatGroupList");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取好友列表
    @Override
    public void getFriendList() {
        try {
            mSessionService.getFriendList();
            LogUtils.i("author" + "getFriendList");
        } catch (Exception e) {

        }
    }

    @Override
    public void getTodoList(int i) {
        try {
            int fromMessageId = 0;
            try {
                fromMessageId = IMApplicationContext.getTodoDomainService().getMaxTodoIdByUserId(
                        mSessionService.getUserId());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            mSessionService.getTodoList(fromMessageId);
            LogUtils.i("author" + fromMessageId + "----------------------fromMessageId");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handMessageIntent(Intent intent) {

    }

    @Override
    public void sendNormalMessage(int msgType, long toId, String pText, MessageSendCallBack callBack) {
        ChatMessage message = sendMessage(new MessageParam(msgType, toId, pText, ChatMessage.CONTENT_TYPE_NORMAL));
        if (callBack != null) {
            callBack.success(message);
        }
    }


    @Override
    public void sendImageMessage(final int msgType, final long toId, String pText) {
        final String fileName = pText.substring(pText.lastIndexOf(File.separator) + 1);


        final ChatMessage message = messageDomainService.makeChatMessage(new MessageParam(msgType
                , toId, pText, "", fileName, ChatMessage.TYPE_JPG, "", ChatMessage.CONTENT_TYPE_ATTACHMENT));
        String fileParam = getFileParam(ChatMessage.TYPE_JPG, pText);
        message.setFileParam(fileParam);
        messageDomainService.addChatMessage(message,
                AccountHelper.getUidInt());
        post(new Event_FileUploadMessage(BEGIN_UPLOAD, message));
        uploadImage(pText, message);
    }

    private void uploadImage(String pText, final ChatMessage message) {
        mFileHttpService.uploadImImage(context, pText, new IFileHttpService.IMFileUploadCallBack() {
            @Override
            public void fail(String msg) {
                post(new Event_FileUploadMessage(ERROR_UPLOAD, message));
            }

            @Override
            public void progress(int progress) {
                post(new Event_FileUploadMessage(UPLOADING, progress, message));
            }

            @Override
            public void success(String fileUrl, String fileName, String fileParam) {
                //获取到传输成功之后七牛云存储地址！
                message.setFilePath(fileUrl);
                message.setFileParam(fileParam);
                messageDomainService.updateChatMessage(message);
                post(new Event_FileUploadMessage(COMPLETE_UPLOAD, message));
                addToWaitQueueAndSend(message);
            }
        });
    }

    @Override
    public void sendFileMessage(final int msgType, final long toId, final String pText) {
        final String fileName = pText.substring(pText.lastIndexOf(File.separator) + 1);
        int chatMessageFileType = ChatMessage.getChatMessageFileType(getExtensionName(fileName));
        final ChatMessage message = messageDomainService.makeChatMessage(new MessageParam(msgType
                , toId, pText, "", fileName, chatMessageFileType, "", ChatMessage.CONTENT_TYPE_ATTACHMENT));

        //因为图片需要先放一个同大小的占位图
        //把gif上传放在这里是因为gif现在没有做压缩，和文件上传相同，后面要压缩后再移动
        String fileParam = getFileParam(chatMessageFileType, pText);
        message.setFileParam(fileParam);
        messageDomainService.addChatMessage(message,
                AccountHelper.getUidInt());
        post(new Event_FileUploadMessage(BEGIN_UPLOAD, message));
        uploadFile(pText, message, fileParam);
    }

    private String getFileParam(int chatMessageFileType, String pText) {
        if (chatMessageFileType >= ChatMessage.TYPE_JPG && chatMessageFileType <= ChatMessage.TYPE_GIF) {
            final int[] fileSize = ImageTools.getFileSize(pText);
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("w", fileSize[0] + "");
                jsonObject.put("h", fileSize[1] + "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject.toString();
        }
        return "";
    }

    private void uploadFile(String pText, final ChatMessage message, final String gifFileParam) {
        mFileHttpService.uploadFile(context, pText, new IFileHttpService.IMFileUploadCallBack() {
            @Override
            public void fail(String msg) {
                post(new Event_FileUploadMessage(ERROR_UPLOAD, message));
            }

            @Override
            public void progress(int progress) {
                post(new Event_FileUploadMessage(UPLOADING, progress, message));
            }

            @Override
            public void success(String fileUrl, String fileName, String fileParam) {
                //获取到传输成功之后七牛云存储地址！
                message.setFilePath(fileUrl);
                if (TextUtils.isEmpty(gifFileParam)) {
                    message.setFileParam(fileParam);
                } else {
                    message.setFileParam(gifFileParam);
                }
                messageDomainService.updateChatMessage(message);
                post(new Event_FileUploadMessage(COMPLETE_UPLOAD, message));
                addToWaitQueueAndSend(message);

            }
        });
    }

    @Override
    public void downLoadFile(final ChatMessage message) {

        if (message.getContent().length() == 0) {
            mFileHttpService.downLoadFile(message.getFilePath(), message.getFileName(), new IFileHttpService.IMFileDownLoadCallBack() {
                @Override
                public void fail(String msg) {
                    post(new Event_FileDownLoadMessage(ERROR_DOWNLOAD, message));
                }

                @Override
                public void progress(int progress) {
                    post(new Event_FileDownLoadMessage(DOWNLOADING, progress, message));
                }

                @Override
                public void success(String fileUrl, String filePath) {
                    message.setContent(filePath);
                    IMApplicationContext.getChatMessageDomainService().updateChatMessageContent(message.getUuid(), filePath);
                    post(new Event_FileDownLoadMessage(COMPLETE_DOWNLOAD, message));
                }
            });
        }

    }


    @Override
    public void sendCustomMessage(int msgType, long toId, String pText, int subType, MessageSendCallBack callBack) {
        ChatMessage message = sendMessage(new MessageParam(msgType, toId, pText, ChatMessage.CONTENT_TYPE_CUSTOM, subType));
        if (callBack != null) {
            callBack.success(message);
        }else {
            post(new Event_SendIMMessageUnCallback(message,null));
        }
    }

    //只在本地数据库加一条记录，红包消息通过创建红包的http已经发送过了
    @Override
    public void sendHongbao(int msgType, long toId, long messageId, String pText, MessageSendCallBack callBack) {
        ChatMessage message = messageDomainService.makeChatMessage(new MessageParam(msgType, toId, pText, ChatMessage.CONTENT_TYPE_HONGBAO));
        message.setStatus(ChatMessage.STATUS_SEND);
        messageDomainService.addChatMessage(message,
                AccountHelper.getUidInt());
        if (callBack != null) {
            callBack.success(message);
        }
    }


    @Override
    public void uploadImImage(Context mContext, String circleImageFileUrl, IFileHttpService.IMFileUploadCallBack imFileUploadCallBack) {
        mFileHttpService.uploadImImage(mContext, circleImageFileUrl, imFileUploadCallBack);
    }

    //发送远程文件
    @Override
    public void sendRemoteFileMessage(int msgType, long toId, String fileName, String fileUrl, int size, MessageSendCallBack callBack) {
        int chatMessageFileType = ChatMessage.getChatMessageFileType(getExtensionName(fileUrl));
        if (TextUtils.isEmpty(fileName)) {
            fileName = OpenFileUtil.extractFileNameFromURL(fileUrl);
        } else {
            fileName = fileName + "." + OpenFileUtil.getExtensionName(fileUrl);
        }

        //获取文件基本信息，如大小
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("size", size);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ChatMessage chatMessage = sendMessage(new MessageParam(msgType, toId, ""
                , fileUrl, fileName, chatMessageFileType, jsonObject.toString(), ChatMessage.CONTENT_TYPE_ATTACHMENT));
        if (callBack != null) {
            callBack.success(chatMessage);
        }
    }

    @Override
    public int getFileProgress(String filePath) {
        return mFileHttpService.getFileProgress(filePath);
    }

    @Override
    public ChatMessage sendMessage(MessageParam messageParam) {
        ChatMessage chatMessage = messageDomainService.makeChatMessage(messageParam);

        //处理断线或连线中的消息
        if (mSessionService == null || !isBindService) {
            m_MsgSendQueue.push(chatMessage);
            //如果n秒后还是没有绑定上就重试一下
            m_handler.removeCallbacksAndMessages(null);
            m_handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mSessionService == null || !isBindService) {
                        onCreate();
                    }
                }
            }, 2000);
        } else {
            sendChatMessage(chatMessage);
        }

        return chatMessage;
    }


    @Override
    public void sendChatMessage(ChatMessage message) {
        messageDomainService.addChatMessage(message,
                AccountHelper.getUidInt());
        addToWaitQueueAndSend(message);
    }

    private void addToWaitQueueAndSend(ChatMessage message) {
        //处理超时
        m_waitQueue.addPacket(message.getUuid(), new WaitSendQueue.IWaitListener() {
            @Override
            public void onStatusOK(String uuid) {
                LogUtils.i("author" + "onStatusOK" + uuid);
            }

            @Override
            public void onTimeout(String uuid) {
                LogUtils.i("author" + "onTimeout" + uuid);
                messageDomainService.updateChatMessageStatus(uuid, ChatMessage.STATUS_FAIL_TIMEOUT);
                post(new Event_MessageTimeOut(uuid));
            }
        });
        try {
            long toId = message.getToId();
            if (message.getMsgType() == ChatMessage.MSG_TYPE_UCG) {
                toId = message.getChatGroupId();
            }
            //如果是发送的文件或者图片，content发送需要为空，用于接收端下载填充用
            String content = message.getContentType() == ChatMessage.CONTENT_TYPE_ATTACHMENT ? "" : message.getContent();

//            UserPhonePOJO userPhonePOJO = AccountHelper.getUserPhonePOJO();
            String userName = "", avator = "";
            int userLevel = 0;
//            if (userPhonePOJO != null) {
//                userName = TextUtils.isEmpty(userPhonePOJO.getUsername()) ? "匿名" : userPhonePOJO.getUsername();
//                avator = TextUtils.isEmpty(userPhonePOJO.getAvatar()) ? "" : userPhonePOJO.getAvatar();
//                userLevel = userPhonePOJO.getGroupIdInt();
//            }

            post(new Event_SendIMMessage(message));

            mSessionService.sendMessage(message.getUuid(), message.getContentType(),
                    content, toId, message.getMsgType(), message.getFilePath(), message.getFileName(), message.getFileType(), message.getFileParam(),
                    userName, avator, userLevel);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    //发送失败之后的二次发送
    @Override
    public void resendMessage(ChatMessage chatMessage, MessageSendCallBack callBack) {
        if (mSessionService == null || !isBindService) {
            return;
        }
        String uuid = UUIDUtil.uuid();
        chatMessage = messageDomainService.replaceChatMessageByUuid(chatMessage.getUuid(), uuid);
        if (callBack != null) {
            callBack.success(chatMessage);
        }
        //如果上传文件失败,需要重新上传
        if (chatMessage.getContentType() == ChatMessage.CONTENT_TYPE_ATTACHMENT && TextUtils.isEmpty(chatMessage.getFilePath())) {
            if (chatMessage.getFileType() == ChatMessage.TYPE_JPG || chatMessage.getFileType() == ChatMessage.TYPE_PNG) {
                uploadImage(chatMessage.getContent(), chatMessage);
            } else {
                uploadFile(chatMessage.getContent(), chatMessage, "");
            }
        } else {
            sendChatMessage(chatMessage);
        }


    }


    @Override
    public void onCreate() {
        LogUtils.d("author" + AccountHelper.isLogin() + " " + (AccountHelper.getUserPhonePOJO() != null));
        if (AccountHelper.isLogin() && AccountHelper.getUserPhonePOJO() != null) {
            startIMService();
        }
    }

    private void startIMService() {
        if (!isBindService && isIM) {
            bindSocket();

            IMApplicationContext.getUserDomainService().getCustomerServiceList();
            worker = new MsgWorker();
            worker.setPacketEventListener(new IMsgEventListener() {

                @Override
                public void onPacket(String type, Bundle bundle) {

                    switch (type) {
                        case Constants.INTENT_ACTION_RECEIVE_CHAT_MESSAGE:
                            final ChatMessage message = (ChatMessage) bundle
                                    .getSerializable(Constants.INTENT_EXTRA_CHAT_MESSAGE);
                            if (message == null) {
                                return;
                            }
                            //保存收到消息的最大id，避免消息被删除
                            saveMaxMsgId(message.getChatMessageId());
                            IMApplicationContext.getUserDomainService().getUser(message.getFromId(), false, new BaseResponseCallBack<String, IMUserEntity>() {
                                @Override
                                public void fail(String msg) {

                                }

                                @Override
                                public void success(IMUserEntity entity) {
                                    sendUserMessageNotification(entity, message);
                                    post(new Event_IMMessage(checkType(message), IMMsgType.RECIEVE));
                                    messageDomainService.sendUncheckCountEvent();
                                }
                            });

                            break;
                        case Constants.INTENT_ACTION_RECEIVE_TODO:
                            Todo todo = (Todo) bundle.getSerializable(Constants.INTENT_EXTRA_TODO);
                            if (todo == null) {
                                return;
                            }
                            sendUserTodoNotification(todo);
                            //需要发送有新好友
                            if (todo.getType() == Todo.TYPE_ADDFRIEND) {
                                post(new Event_FriendRequestAdd());
                            }
                            todoDomainService.sendUncheckCountEvent();
                            break;
                        case Constants.INTENT_ACTION_RECEIVE_CHAT_MESSAGE_LIST:
                            post(new Event_IMMessageList());
                            messageDomainService.sendUncheckCountEvent();
                            long maxMessageIdByUserId = messageDomainService.getMaxMessageIdByUserId(AccountHelper.getUidInt());
                            saveMaxMsgId(maxMessageIdByUserId);

                            break;
                        case Constants.INTENT_ACTION_RECEIVE_RECEIPT_MESSAGE://收到消息回执！
                            LogUtils.i("author" + "分发消息回执");
                            String receiptUuid = bundle.getString(Params.RECEIPT_UUID);
                            //默认失败！
                            int receiptStatus = bundle.getInt(Params.RECEIPT_STATUS, 4);
                            m_waitQueue.checkUpdate(receiptUuid);
                            post(new Event_ReceiptMessage(receiptUuid, receiptStatus, IMMsgType.RECIEVE));

                            break;
                        case Constants.INTENT_ACTION_RECEIVE_FRIEND_LIST:
                            LogUtils.i("author" + "get friend list work");
                            post(new Event_FriendList());
                            break;
                        case Constants.INTENT_ACTION_RECEIVE_FRIEND_GROUP_LIST:
                            LogUtils.i("author" + "get group list work");
                            post(new Event_GroupList());
                            break;
                        case Constants.INTENT_ACTION_RECEIVE_TODO_LIST://TODO  todo数据暂时不需要通知，如果需要通知发送Event
                            todoDomainService.sendUncheckCountEvent();

                            break;
                        case Constants.INTENT_ACTION_RECEIVE_LOGIN_MESSAGE:
                            boolean loginResult = bundle.getBoolean(Params.LOGIN_STATUS);
                            if (loginResult) {
                                try {
                                    LogUtils.i("author" + "登陆成功，准备获取离线");
                                    getMessageList();
                                    getChatGroupList();
                                    getFriendList();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    LogUtils.i("author" + "获取  SessionService！失败，AIDL失败");
                                }
                            }
                            break;
                        case Constants.INTENT_ACTION_ADD_FRIENDS:
                            post(new Event_AddFriends());
                            break;
                        case Constants.INTENT_ACTION_DELETE_FRIENDS:
                            post(new Event_DeleteFriends());
                            break;
                        case Constants.INTENT_ACTION_ADD_CIRCLE:
                            post(new Event_AddCircles());
                            break;
                        case Constants.INTENT_ACTION_DELETE_CIRCLE:
                            post(new Event_DeleteCircles());
                            break;
                        default:
                            break;
                    }
                }

            });

            beepManager = BeepManager.getInstance(context);
            //监听响铃和震动的改变
            imBeepReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    beepManager.updatePrefs();
                }
            };
            beepFilter = new IntentFilter(
                    AudioManager.RINGER_MODE_CHANGED_ACTION);
            context.registerReceiver(imBeepReceiver, beepFilter);
        }
    }

    /**
     * 保存最大的消息id，避免动态获取的话有可能用户删除了消息又获取了回来
     * @param msgId
     */
    private void saveMaxMsgId(long msgId) {
        long maxMsgId = UserSharedPreferenceUtil.getLong(context, Constants.MAX_CHATMESSAGE_ID_LONG, 0);
        if (msgId > maxMsgId) {
            UserSharedPreferenceUtil.putLong(context, Constants.MAX_CHATMESSAGE_ID_LONG, msgId);
        }
    }


    private void sendUserTodoNotification(Todo todo) {
        String title = "", content = "", deepLink = "";
        beepManager.playBeepSoundAndVibrate();

        if (todo.getType() == Todo.TYPE_ADDFRIEND) {
            title = "收到一条好友请求";
            deepLink = "blockmeta://im/friend";

        } else if (todo.getType() == Todo.TYPE_JOINCIRCLE) {
            title = "收到一条加圈请求";
            deepLink = "blockmeta://im/chatgroup_detail?id=" + todo.getGroupId();
        }
        NotificationHelper.getInstance(context).sendNotification(title, content, deepLink,
                todo.getFromId(), -1);
    }

    private void sendUserMessageNotification(IMUserEntity entity, ChatMessage message) {
        String title = "", content = "", deepLink = "";
        boolean isNoDisturb = false;
        if (message.getMsgType() == ChatMessage.MSG_TYPE_UCG) {
            isNoDisturb = IMApplicationContext.getCircleDomainService().isCircleDisturb(message.getChatGroupId());
        }
        isNoDisturb = (message.getContentType() == ChatMessage.CONTENT_TYPE_NONOTIFY ? true : isNoDisturb);
        //如果不是群设置的免打扰
        if (!isNoDisturb) {
            //如果app在前台则不弹通知
            boolean isForeground = ForegroundCallbacks.get(BaseApp.getApp()).isAppForground();
            if (!isForeground) {
                if (message.getMsgType() == ChatMessage.MSG_TYPE_UU) {
                    title = TextUtils.isEmpty(entity.getRemarkName()) ? entity.getName() : entity.getRemarkName();
                    content = messageDomainService.getShowContent(null, message);
                    deepLink = "blockmeta://im/chat" + "?id=" + message.getFromId();

                } else if (message.getMsgType() == ChatMessage.MSG_TYPE_UCG) {
                    title = "圈子群聊";
//                    IMUserEntity userEntity = IMApplicationContext.getUserDomainService().getUser(message.getFromId(), Params.USER_PERSON);
                    content = messageDomainService.getShowContent(entity, message);
                    deepLink = "blockmeta://im/chatgroup" + "?id=" + message.getChatGroupId();
                }
                long fromId = message.getMsgType() == ChatMessage.MSG_TYPE_UU ? message.getFromId() : message.getChatGroupId();
                NotificationHelper.getInstance(context).sendNotification(title, content, deepLink,
                        fromId, message.getMsgType());
            } else {
                //弹出通知，系统会有声音，在前台需要声音去提醒
                beepManager.playBeepSoundAndVibrate();
            }
        }
    }


    private void bindSocket() {

        String userToekn = AccountHelper.getToken();
        UserPhonePOJO UserPhonePOJO = AccountHelper.getUserPhonePOJO();
        if (UserPhonePOJO == null) {
            return;
        }
        LogUtils.d("authorkkk" + "bindSocket" + userToekn + "userpojo:" + UserPhonePOJO.toString());
        if (TextUtils.isEmpty(userToekn)) {
            return;
        }

        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        boolean isForeground = ForegroundCallbacks.get(BaseApp.getApp()).isAppForground();

        mIntentService = new Intent(Constants.INTENT_SERVICE_SESSION);
        mIntentService.setAction(Constants.INTENT_SERVICE_SESSION);
        mIntentService.setPackage(provider.getProjectBuildInfo().application_id);
        mIntentService.putExtra(Params.Seriliza_UserPOJO, UserPhonePOJO);
        mIntentService.putExtra(Params.Seriliza_Token, userToekn);
        //如果应用在后台使用startforegroudservice
        if (isForeground) {
            context.startService(mIntentService);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mIntentService.putExtra(Params.APPBACKGROUND, true);
                context.startForegroundService(mIntentService);
            } else {
                context.startService(mIntentService);
            }
        }
        context.bindService(mIntentService, connection, Context.BIND_AUTO_CREATE);
        isBindService = true;

        m_MsgSendQueue.sendAll();
    }

    @Override
    public boolean isBindService() {
        return mSessionService != null && isBindService;
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mSessionService = SessionService.Stub.asInterface(service);
            try {
                mSessionService.setCallBack(new ICallBack.Stub() {
                    @Override
                    public void onReceiveData(Intent intent) throws RemoteException {
                        String key = intent.getAction();
                        LogUtils.d("pid session callback " + android.os.Process.myPid());

                        LogUtils.i("author" + "IMDataReceiver" + key + " " + intent.getData());
                        if (!TextUtils.isEmpty(key)) {
                            IMMsgDispatcher.getInstance().dispatch(key, intent);
                        } else {
                        }
                    }
                });
            } catch (RemoteException e) {
                LogUtils.e("onServiceConnected " + e.getMessage());
                e.printStackTrace();
            } catch (Exception e){
                LogUtils.e("onServiceConnected1 " + e.getMessage());
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            onStopServer();
            //登录状态下需要重新启动和绑定
            IMApplicationContext.getIMMetaService().onCreate();
        }
    };

    @Override
    public void onConnectCreate() {

    }

    /**
     * 关闭服务
     */
    @Override
    public synchronized void onStopServer() {
        LogUtils.d("authorkkk" + "im onstopserver");
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        mIntentService = new Intent(Constants.INTENT_SERVICE_SESSION);
        mIntentService.setAction(Constants.INTENT_SERVICE_SESSION);
        mIntentService.setPackage(provider.getProjectBuildInfo().application_id);
        context.unbindService(connection);
        context.stopService(mIntentService);
        m_waitQueue.closeConnection();
        m_MsgSendQueue.clear();
        mSessionService = null;
        isBindService = false;
        context.unregisterReceiver(imBeepReceiver);


    }


    /**
     * 消息类型中转检查判断
     *
     * @param pMsg
     * @return
     */
    private ChatMessage checkType(ChatMessage pMsg) {
        ChatMessage tResult = pMsg;

        return tResult;
    }

    private String checkType(String msg) {
        String tResult = msg;
        return tResult;
    }
}
